<script setup>
import { reactive, ref } from 'vue'
import useLoginStore from '@/stores/user/index.js'
import { ElMessage } from 'element-plus'
import { setLocalStore } from '@/utils/localUser.js'
import router from '@/router/index.js'

const loginStore = useLoginStore()
const loginRef = ref()

const loginParams = reactive({
  phone: '',
  password: ''
})

const rules = reactive({
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ]
})

//登录
const loginBtn = async () => {
  //校验表单

  await loginRef.value.validate()
  if (loginStore.info === '立即登录') {
    const res = await loginStore.loginAction(loginParams)
    if (res.code === 1) {
      //存储用户信息
      setLocalStore('token', loginStore.userInfo.token)
      setLocalStore('userInfo', loginStore.userInfo)
      ElMessage.success('登录成功')
      //再次刷新页面
      location.reload()
      router.go(0)
    } else {
      ElMessage.error(res.msg)
      return
    }
  } else {
    const res = await loginStore.registerAction(loginParams)
    if (res.code === 1) {
      //存储用户信息
      ElMessage.success('注册成功')
    } else {
      ElMessage.error(res.msg)
      return
    }
  }

  //关闭弹窗
  loginStore.isShow = false
}
</script>

<template>
  <div class="login">
    <el-dialog v-model="loginStore.isShow" title="登录后内容更精彩" width="500px">
      <span class="title">手机登录</span>
      <el-form ref="loginRef" :rules="rules" :model="loginParams" label-width="auto">
        <el-form-item prop="phone">
          <el-input v-model="loginParams.phone" prefix-icon="UserFilled" placeholder="手机号" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            show-password
            v-model="loginParams.password"
            prefix-icon="Lock"
            placeholder="密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="loginBtn"
            >{{ loginStore.info }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.login {
  :deep(.el-dialog) {
    background-color: #f2f2f2;
  }

  .el-form {
    margin: 20px 100px;
  }

  .title {
    color: #222;
    margin-left: 100px;
  }

  .content {
    display: flex;
    justify-content: center;

    .card {
      .title {
        text-align: center;
        font-weight: normal;
        color: #707070;
        margin-bottom: 30px;
      }
    }
  }

  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
